package db

import (
	"center/db/models"
	"common/uuid"
	"context"
	"crypto/rand"
	"errors"
	"gorm.io/gorm"
)

type CreateUserParam struct {
	ID           uuid.UUID
	Username     string
	Email        string
	PasswordHash []byte
}

// CreateUser 新建用户，会创建默认bucket
func (d *CenterDB) CreateUser(ctx context.Context, param *CreateUserParam) (user *models.User, err error) {
	secret := make([]byte, 16)
	_, err = rand.Read(secret)
	if err != nil {
		return
	}
	user = &models.User{
		ID:           param.ID,
		Username:     param.Username,
		Email:        param.Email,
		PasswordHash: param.PasswordHash,
		SecretKey:    secret,
	}
	//新建用户都会创建一个默认的bucket
	err = d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		err = tx.Create(&user).Error
		if err != nil {
			return err
		}
		var bid uuid.UUID
		bid, err = uuid.New()
		if err != nil {
			return err
		}
		return tx.Create(&models.Bucket{ID: bid, Bucket: DefaultBucketName, OwnerId: user.ID}).Error
	})
	return
}

func (d *CenterDB) GetUserByEmail(ctx context.Context, email string) (user *models.User, err error) {
	err = d.db.WithContext(ctx).Where("email = ?", email).Take(&user).Error
	return
}

func (d *CenterDB) ExistsUserByEmail(ctx context.Context, email string) (bool, error) {
	var user models.User
	err := d.db.WithContext(ctx).Where("email = ?", email).Take(&user).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, nil
		}
		return false, err
	}
	return true, err
}
